<template>
  <el-space>
    <el-input
      :style="{ width: '320px' }"
      placeholder="快速发现你的电影"
      size="large"
      search-button
      v-model="movieName"
    />
    <el-button @click="searchMovie">搜索</el-button>
  </el-space>
  <el-row style="margin-bottom: 16px" align="center" :wrap="false">
    <el-col v-for="item in dataList" :key="item.id" :span="6" :id="item.id">
      <MovieCard :movie="item" />
    </el-col>
  </el-row>
  <el-pagination
    :page-size="searchParams.pageSize"
    :current-page="searchParams.current"
    @size-change="onPageChange"
    @current-change="onPageChange"
    layout="prev, pager, next"
    :page-count="pageCount"
  />
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch, watchEffect } from "vue";
import API from "@/api";
import { listMovieVoByPageUsingPost } from "@/api/movieController";
import { ElMessage } from "element-plus";
import MovieCard from "@/components/MovieCard.vue";
import router from "@/router";

// 初始化搜索条件（不应该被修改）
const initSearchParams = {
  current: 1,
  pageSize: 8,
};

const movieName = ref<string>("");

const searchParams = ref<API.MovieQueryRequest>({
  ...initSearchParams,
});
const dataList = ref<API.MovieVO[]>([]);
const pageCount = ref<number>(5);

const searchMovie = () => {
  searchParams.value = {
    ...searchParams.value,
    movieName: movieName.value,
  };
};

/**
 * 加载数据
 */
const loadData = async () => {
  const res = await listMovieVoByPageUsingPost(searchParams.value);
  if (res.data.code === 0) {
    dataList.value = res.data.data?.records || [];
    pageCount.value = Math.ceil(
      (res.data.data?.total as number) / searchParams?.value?.pageSize ?? 5
    );
  } else {
    ElMessage({
      message: "获取数据失败，" + res.data.message,
      type: "error",
    });
  }
};

/**
 * 当分页变化时，改变搜索条件，触发数据加载
 * @param page
 */
const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

watchEffect(() => {
  loadData();
});
</script>

<style scoped>
#home {
}
</style>
